import BaseFormWidget from './BaseFormWidget.js';
import { getOpt } from "../tools.js";


const InputWidget = BaseFormWidget.extend({
    /*
     * A base input widget
     *
     * Support following options :
     *
     *    * value
     *    * title or label
     *    * field_name
     *    * description
     *    * type (default text)
     *    * addon (bootstrap addon)
     *    * css_class: A custom css class
     *    * editable
     *    * placeholder
     *    * ariaLabel
     *    * dataList
     *    * editable
     *
     *    new InputWidget({'title': 'My label', 'field_name': 'field1});
     *
     *  Trigger 2 types of events :
     *
     *      * change (onKeyUp)
     *      * finish (onBlur)
     *
     *      with parameters :
     *
     *      field_name
     *      value
     *
     */
    tagName: 'div',
    className: 'form-group',
    template: require('./templates/InputWidget.mustache'),
    ui: {
        input: 'input'
    },
    events: {
        'keyup @ui.input': 'onKeyUp',
        'blur @ui.input': 'onBlur',
    },
    onKeyUp: function(){
        this.triggerChange(this.getUI('input').val());
    },
    onBlur: function(){
        this.triggerFinish(this.getUI('input').val());
    },
    templateContext: function(){
        let result = this.getCommonContext();
        let type = getOpt(this, "type", "text");
        if ((!result.label) && (!result.ariaLabel) && (type != 'hidden')){
            result.description += 'Warning : no ariaLabel provided';
        }
        // update returned dict
        result = Object.assign(
            result,
            {
                type: type,
                value: this.getOption('value'),
                css_class: getOpt(this, 'css', ''),
                dataList: getOpt(this, 'dataList', []),
                uniqueId: _.uniqueId('datalist'),
                pattern: this.getOption('pattern'),
            }
        );
        return result;
    }
});


export default InputWidget;
